import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { getTenant } from '../api/base/region'
import { Tenant } from '../types/Tenant'
import { boardSchoolStore } from './modules/board-school'
import { User } from '/@/types/User'
import axios from '/@/api/axios'

export interface Todo {
  qty: number
  data: any[]
}

export interface RootState {
  count: number
  showTabbar: boolean
  user?: any
  userInfo: User
  userInfoMap: any
  childrenUsers: any
  todoData: Todo
  tenant: Tenant
  levelOptions: Array<Object>
  enterprise: Array<string>
}

// 定义 injection key
export const key: InjectionKey<Store<RootState>> = Symbol()

// 创建一个新的 store 实例
const store = createStore<RootState>({
  modules: {
    boardSchoolStore,
  },
  state() {
    return {
      count: 0,
      showTabbar: true,
      user: null as any, // 当前用户信息（字段较少）
      userInfo: null as any, // 当前用户详情
      userInfoMap: {} as User, // 用户详情集合，{11122: {}, 11123: {}}
      childrenUsers: {}, // 家长对应小孩的集合，{parentId1: [{},{}], ...}
      // 待办事项
      todoData: {
        qty: 0, // 总待办数量
        data: [
          // 按类型统计的待办数量
          // {
          //   name: '学生测评',
          //   qty: 10, // 未完成的数量
          // },
        ],
      },
      tenant: {} as Tenant,
      levelOptions: [] as Array<Object>, // 所有预警级别的数据选项
      enterprise: ['508655', '150291', '059420'],
    }
  },
  mutations: {
    increment(state) {
      // state.count++
    },
    setShowTabbar(state, val) {
      // state.showTabbar = val
    },
    setUser(state: any, val: any) {
      state.user = val
    },
    setUserInfo(state: any, val: User) {
      state.userInfo = val
    },
    setUserInfoMap(state: any, val: any) {
      state.userInfoMap[val.userId || val.id] = val
    },
    setTodoData(state: any, val: any) {
      state.todoData.qty = val.qty || 0
      state.todoData.data = val.data || []
    },
    setChildrenUsers(state: any, val: any) {
      state.childrenUsers[val.key] = val.value || []
    },
    setTenant(state, val) {
      state.tenant = val
    },
    setLevelOptions(state, val) {
      state.levelOptions = val
    },
  },
  actions: {
    async getTenant({ commit, state }) {
      const {
        data: { data },
      } = await getTenant(state.user?.tenantId || state.userInfo?.tenantId)
      commit('setTenant', data)
    },
    async initLevelOptions({ commit, state }) {
      if (state.levelOptions && state.levelOptions.length) {
        return state.levelOptions
      }
      let { data } = await axios({
        url: '/api/blade-system/dict/dictionary?code=warning_level',
        method: 'get',
        params: {},
      })
      commit(
        'setLevelOptions',
        (data.data || []).map((r: any) => {
          return {
            value: r['dictKey'],
            name: r['dictValue'],
          }
        })
      )
    },
  },
})

export default store

export function useStore() {
  return baseUseStore(key)
}
